<template>
  <div class="app-container search-table-box aidex-table">
    <el-card shadow="never" ref="queryRef" style="margin-bottom: 12px;" class="search_card" v-show="showSearch">
      <div class="filter-container">
        <div class="search_box">
          <el-form :model="queryParams" ref="queryForm" label-width="80px" size="mini">
            <el-row :gutter="2">
              <el-col :md="5" >
                <el-form-item prop="searchValues">
                  <el-select
                    v-model="queryParams.searchValues"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    clearable
                    placeholder="请输入组织名称/电话/账号"
                    :remote-method="remoteSearchValue"
                    @change="handleQuery"
                    :loading="remoteSearchValueLoading"
                    style="width: 415px;margin-left: -78px"
                  >
                    <el-option
                      v-for="item in searchValueOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :md="6" align="right">
                <el-form-item>
                  <el-button class="filter-item" type="primary" @click="handleQuery">搜索</el-button>
                  <el-button class="filter-item" style="margin-left: 8px" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </el-card>
    <el-card shadow="never" >
      <template #header>
        <el-row>
          <el-col :span="8">
            <div class="card-header">
              <el-button disabled type="text">组织信息</el-button>
            </div>
          </el-col>
          <el-col :span="16">
            <div class="btn_box" align="right" style="float: right;">
              <el-button
                class="filter-item"
                style="margin-left: 8px;"
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd"
                size="mini"
                v-hasPermi="['system:site:add']"
              >新增</el-button>
              <el-button
                class="filter-item"
                style="margin-left: 8px;"
                icon="el-icon-delete"
                type="danger"
                :disabled="multiple"
                @click="handleDelete"
                size="mini"
                v-if="!multiple"
                v-hasPermi="['system:site:remove']"
              >删除</el-button>
              <el-button
                class="filter-item"
                style="margin-left: 8px;"
                icon="el-icon-download"
                @click="handleExport"
                size="mini"
                v-hasPermi="['system:site:export']"
              >导出</el-button>
              <right-toolbar :showSearch.sync="showSearch" :columns.sync="columns" :columnsKey.sync="columnsKey" @showSearchFun="showSearchFun" @queryTable="getList" :tableKey.sync="tableKey"></right-toolbar>
            </div>
          </el-col>
        </el-row>
      </template>

      <el-table
              border
              stripe
              default-expand-all
              ref="tableRef"
              :key="tableKey"
              v-loading="loading"
              :data="siteList"
              @selection-change="handleSelectionChange"
              :row-style="rowClass"
              :header-cell-style= "{
                'font-size': '14px !important',
                'font-weight': '500 !important',
                'color': 'rgb(0 0 0)',
                'background-color': 'rgb(205 224 255)',
              }"
              highlight-current-row style="width: 100%;"
              :height="tableHeight"
      >
        <el-table-column type="selection" width="55" align="left" />
        <el-table-column label="序号" type="index" align="left" width="55">
          <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>

        <template v-for="item in columns">
          <el-table-column label="组织编码" align="left" prop="siteCode" v-if="item.visible && item.label=='组织编码'" width="140px" show-overflow-tooltip/>
          <el-table-column label="组织名称" align="left" prop="siteName" v-if="item.visible && item.label=='组织名称'" width="180px"  show-overflow-tooltip/>
          <el-table-column label="纳税识别号" align="left" prop="taxNumber" v-if="item.visible && item.label=='纳税识别号'" width="180px" show-overflow-tooltip/>
          <el-table-column label="所属税局" align="left" prop="taxDeptName" v-if="item.visible && item.label=='所属税局'" width="120px" show-overflow-tooltip/>
          <el-table-column label="企业性质" align="left" prop="propertyTypeName" v-if="item.visible && item.label=='企业性质'" width="120px" show-overflow-tooltip/>
          <el-table-column label="所属行业" align="left" prop="propertyIndustry" v-if="item.visible && item.label=='所属行业'" width="140px" show-overflow-tooltip/>
<!--          <el-table-column label="发票类型" align="left" prop="invoiceTypeNames" v-if="item.visible && item.label=='发票类型'" width="140px" show-overflow-tooltip/>-->
          <el-table-column label="地址" align="left" prop="address" v-if="item.visible && item.label=='地址'"  width="160px" show-overflow-tooltip/>
          <el-table-column label="电话" align="left" prop="tel" v-if="item.visible && item.label=='电话'"  width="120px" show-overflow-tooltip/>
          <el-table-column label="开户行" align="left" prop="bankName" v-if="item.visible && item.label=='开户行'"  width="160px" show-overflow-tooltip/>
          <el-table-column label="账号" align="left" prop="accountNo" v-if="item.visible && item.label=='账号'"  width="160px" show-overflow-tooltip/>
          <el-table-column label="收款人" align="left" prop="paymentBy" v-if="item.visible && item.label=='收款人'"  width="120px" show-overflow-tooltip/>
          <el-table-column label="复核人" align="left" prop="receiveBy" v-if="item.visible && item.label=='复核人'"  width="120px" show-overflow-tooltip/>
          <el-table-column label="开票人" align="left" prop="invoiceBy" v-if="item.visible && item.label=='开票人'"  width="120px" show-overflow-tooltip/>
          <el-table-column label="创建时间" align="left" prop="createTime" width="180" v-if="item.visible && item.label=='创建时间'" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="修改人" align="left" prop="updateBy" v-if="item.visible && item.label=='修改人'" show-overflow-tooltip/>
          <el-table-column label="修改时间" align="left" prop="updateTime" width="180" v-if="item.visible && item.label=='修改时间'" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
        </template>

        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:site:edit']"
            >修改</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button
              type="text"
              @click="handleShowUser(scope.row)"
              v-hasPermi="['system:site:user']"
            >查看用户</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <svg-icon icon-class="search-none" style="font-size: 64px;" />
          <p>暂无数据</p>
        </div>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改客户组织对话框 -->
      <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px" top="10vh" append-to-body>
        <div style="height: 490px;overflow: auto; padding: 12px 24px;">
          <el-form ref="form" size="mini" :model="form" :rules="rules" label-position="right" label-width="90px">
            <el-divider content-position="left">基础信息</el-divider>
            <el-row :gutter="12">
              <el-col :span="6">
                <el-form-item label="组织编码" prop="siteCode">
                  <el-tag v-if="form.siteCode">{{form.siteCode}}</el-tag>
                  <el-tag type="info" v-else>系统自动生成</el-tag>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="12">
              <el-col :span="12">
                <el-form-item label="组织名称" prop="siteName">
                  <el-input v-model="form.siteName" placeholder="请输入组织名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属行业" prop="propertyIndustry">
                  <el-input v-model="form.propertyIndustry" placeholder="请输入所属行业" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纳税识别号" prop="taxNumber">
                  <el-input v-model="form.taxNumber" placeholder="请输入纳税识别号" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="所属税局" prop="taxDeptName">
                  <el-select clearable v-model="form.taxDept">
                    <el-option v-for="(dict,index) of dict.type.tax_dept" :key="index" :label="dict.label" :value="parseInt(dict.value)">{{dict.label}}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="企业性质" prop="propertyTypeName">
                  <el-select clearable v-model="form.propertyType">
                    <el-option v-for="(dict,index) of dict.type.property_type" :key="index" :label="dict.label" :value="parseInt(dict.value)">{{dict.label}}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="12">
              <el-divider content-position="left">基础信息</el-divider>
<!--              <el-col :span="24">-->
<!--                <el-form-item label="发票类型" prop="invoiceTypeNames">-->
<!--                  <el-checkbox v-model="checkAllInvoiceType" :indeterminate="isInvoiceTypeIndeterminate" label="全选" size="mini" @change="checkAll($event,'invoiceType')" ></el-checkbox>-->
<!--                  <el-checkbox-group v-model="form.invoiceTypeArr" @change="handleCheckedChange($event,'invoiceType')">-->
<!--                    <el-checkbox v-for="dict in dict.type.invoice_type" :label="dict.value" :key="dict.value">{{dict.label}}</el-checkbox>-->
<!--                  </el-checkbox-group>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
              <el-col :span="24">
                <el-form-item label="地址" prop="address">
                  <el-input v-model="form.address" placeholder="请输入地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开户行" prop="bankName">
                  <el-input v-model="form.bankName" placeholder="请输入开户行" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="电话" prop="tel">
                  <el-input v-model="form.tel" placeholder="请输入电话" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="开票人" prop="invoiceBy">
                  <el-input v-model="form.invoiceBy" placeholder="请输入开票人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="账号" prop="accountNo">
                  <el-input v-model="form.accountNo" placeholder="请输入账号" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="收款人" prop="paymentBy">
                  <el-input v-model="form.paymentBy" placeholder="请输入收款人" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="复核人" prop="receiveBy">
                  <el-input v-model="form.receiveBy" placeholder="请输入复核人" />
                </el-form-item>
              </el-col>

            </el-row>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary"  size="mini" @click="submitForm">确 定</el-button>
          <el-button  size="mini" @click="cancel">取 消</el-button>
        </div>
      </el-dialog>



    </el-card>
  </div>
</template>

<script>
import { listSite, getSite, delSite, addSite, updateSite } from "@/api/system/site";
/* 城市列表 **/
import { provinceList, cityList, districtList } from "@/api/system/city";

export default {
  name: "Site",
  dicts: ['tax_dept','invoice_type','property_type'],
  data() {
    return {
      advanced: false,
      tableHeight: this.getInitTableHeight(),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户组织表格数据
      siteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params:{

        },
        searchValues: [],
        custId: null,
        siteCode: null,
        siteName: null,
        taxNumber: null,
        taxDept: null,
        taxDeptName: null,
        propertyType: null,
        propertyTypeName: null,
        propertyIndustry: null,
        invoiceTypes: null,
        invoiceTypeNames: null,
        address: null,
        tel: null,
        bankName: null,
        accountNo: null,
        paymentBy: null,
        receiveBy: null,
        invoiceBy: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },

      // 远程查询条件加载
      remoteSearchValueLoading: false,
      // 关键字查询条件
      searchValueOptions:[

      ],
      // 表单参数
      form: {
          invoiceTypeArr: []
      },
      // 表单校验
      rules: {
          siteName: [
              { required: true, message: "组织名称不能为空", trigger: "blur" }
          ],
          taxNumber: [
              { required: true, message: "纳税识别号不能为空", trigger: "blur" }
          ],
          taxDept: [
              { required: true, message: "所属税局不能为空", trigger: "blur" }
          ],
          propertyType: [
              { required: true, message: "企业性质不能为空", trigger: "blur" }
          ],
          address: [
              { required: true, message: "地址不能为空", trigger: "blur" }
          ],
          tel: [
              { required: true, message: "电话不能为空", trigger: "blur" }
          ],
          bankName: [
              { required: true, message: "开户行不能为空", trigger: "blur" }
          ],
          accountNo: [
              { required: true, message: "账号不能为空", trigger: "blur" }
          ],
      },
      checkAllInvoiceType: false,
      isInvoiceTypeIndeterminate: false,
      tableKey: 11,
      //
      columnsKey: 'site',
      // 自定义列
      columns: [
          {
              key: 0,
              label: `组织编码`,
              visible: true
          },
          {
              key: 1,
              label: `组织名称`,
              visible: true
          },
          {
              key: 2,
              label: `纳税识别号`,
              visible: true
          },
          {
              key: 3,
              label: `所属税局`,
              visible: true
          },
          {
              key: 4,
              label: `企业性质`,
              visible: true
          },
          {
              key: 5,
              label: `所属行业`,
              visible: true
          },
          {
              key: 7,
              label: `地址`,
              visible: true
          },
          {
              key: 8,
              label: `电话`,
              visible: true
          },
          {
              key: 9,
              label: `开户行`,
              visible: true
          },
          {
              key: 10,
              label: `账号`,
              visible: true
          },
          {
              key: 11,
              label: `收款人`,
              visible: true
          },
          {
              key: 12,
              label: `复核人`,
              visible: true
          },
          {
              key: 13,
              label: `开票人`,
              visible: true
          },
          {
              key: 14,
              label: `创建时间`,
              visible: true
          },
          {
              key: 15,
              label: `修改人`,
              visible: true
          },
          {
              key: 16,
              label: `修改时间`,
              visible: true
          }
      ],
      /* ======================================省市区======================================  */
      // 省
      provinceId: null,
      provinceList:[],
      // 市
      cityId: null,
      cityList:[],
      // 区
      districtId: null,
      districtList:[],

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 行样式 */
    rowClass({ row, rowIndex }) {
      if (this.ids.includes(row.id)) {
          return { background: "#d9edf7", height:'20px' };
      } else {
          return { height:'20px'};
      }
    },
   /** 隐藏搜索按钮操作 */
   showSearchFun(isShowSearch){
      this.showSearch = isShowSearch
      let oldHeight = this.$refs.queryRef.$el.offsetHeight
      if(!isShowSearch){
          //当前是显示状态
          oldHeight = oldHeight + 12
      }else{
          oldHeight = oldHeight - 12
      }
      this.$nextTick(() => (
         this.tableHeight = this.$refs.tableRef.$el.offsetHeight - (this.$refs.queryRef.$el.offsetHeight-oldHeight)
      ))
    },
    /** 展开按钮操作 */
    toggleAdvanced() {
      const oldHeight = this.$refs.queryRef.$el.offsetHeight
      this.advanced = !this.advanced
      this.$nextTick(() => (
         this.tableHeight = this.$refs.tableRef.$el.offsetHeight - (this.$refs.queryRef.$el.offsetHeight-oldHeight)
      ))
    },
    /** 查询客户组织列表 */
    getList() {
      this.loading = true;
      listSite(this.queryParams).then(response => {
        this.siteList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        custId: null,
        siteCode: null,
        siteName: null,
        taxNumber: null,
        taxDept: null,
        taxDeptName: null,
        propertyType: null,
        propertyTypeName: null,
        propertyIndustry: null,
        invoiceTypes: null,
        invoiceTypeNames: null,
        address: null,
        tel: null,
        bankName: null,
        accountNo: null,
        paymentBy: null,
        receiveBy: null,
        invoiceBy: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        invoiceTypeArr: []
      };
      this.resetForm("form");
    },


      /* ※※ 查询 省市区 相关方法 start ※※ */
      // 获取省
      getProvinceList(){
          provinceList().then(response => {
              this.provinceList = response.data;
          });
      },
      // 获取市
      getCityList(){
          console.log(this.provinceId);
          cityList( {"parentId" : this.provinceId } ).then(response => {
              this.cityList = response.data;
          });
      },
      // 获取区县
      getDistrictList(){
          districtList( {"parentId" : this.cityId } ).then(response => {
              this.districtList = response.data;
          });
      },
      // 选中省份
      handleChangeProvince(val){
          // 给表单省字段赋值
          this.form.provinceid = val;
          let province = {};
          province = this.provinceList.find((item)=>{
              return item.id === val;
          });
          this.form.province = province.name;
          // 城市数据清空、区县数据清空;
          this.cityList = [];
          this.districtList = [];
          // 已选市、区数据清空
          this.cityId = null;
          this.districtId = null;
          // 表单城市、区县数据清空
          this.form.cityid = null;
          this.form.city = null;
          this.form.areaid = null;
          this.form.area = null;
          // 获取城市数据
          this.getCityList();
      },
      // 清空省份
      handleClearProvince(){
          // 城市数据清空、区县数据清空;
          this.cityList = [];
          this.districtList = [];
          // 已选市、区数据清空
          this.cityId = null;
          this.districtId = null;
          // 表单城市、区县数据清空
          this.form.cityid = null;
          this.form.city = null;
          this.form.areaid = null;
          this.form.area = null;
      },
      // 选中城市
      handleChangeCity(val){
          // 给表单市字段赋值
          this.form.cityid = val;
          let city = {};
          city = this.cityList.find((item)=>{
              return item.id === val;
          });
          this.form.city = city.name;
          // 区县数据清空
          this.districtList = [];
          // 已选区县清空
          this.districtId = null;
          // 表单区县清空
          this.form.areaid = null;
          this.form.area = null;
          // 获取城市数据
          this.getDistrictList();
      },
      // 清空省份
      handleClearCity(){
          // 区县数据清空
          this.districtList = [];
          // 已选区县清空
          this.districtId = null;
          // 表单区县清空
          this.form.areaid = null;
          this.form.area = null;
      },
      // 选中区县
      handleChangeDistrict(val){
          // 给表单省字段赋值
          this.form.areaid = val;
          let district = {};
          district = this.districtList.find((item)=>{
              return item.id === val;
          });
          this.form.area = district.name;
      },
      // 清空省份
      handleClearDistrict(){
          // 表单区县清空
          this.form.areaid = null;
          this.form.area = null;
      },

      /* ※※ 查询 省市区 相关方法 end ※※ */




    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户组织";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSite(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户组织";
      });
    },
    /** 查看用户按钮操作 */
    handleShowUser(row) {
      this.reset();
      const id = row.id || this.ids
      getSite(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户组织";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // if(this.form.invoiceTypeArr){
          //     this.form.invoiceTypes = this.form.invoiceTypeArr.join(",");
          // } else {
          //     this.$modal.msgError("发票类型不能为空"); return;
          // }
          if (this.form.id != null) {
            updateSite(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSite(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户组织编号为"' + ids + '"的数据项？').then(function() {
        return delSite(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/site/export', {
        ...this.queryParams
      }, `site_${new Date().getTime()}.xlsx`)
    },

    /** 动态加载关键字查询条件 */
    remoteSearchValue(query) {
        this.remoteSearchValueLoading = true;
        if (query !== '') {
            this.searchValueOptions = [
                {value: '组织名称:' + query ,label: '组织名称:' + query },
                {value: '电话:' + query ,label: '电话:' + query },
                {value: '账号:' + query ,label: '账号:' + query },
            ];
            this.searchValueOptions.map(item => {
                this.queryParams.searchValues.map((item2, index) => {
                    if(item.value.startsWith('组织名称') && item2.startsWith('组织名称')){
                        item.disabled = true;
                    }
                    if(item.value.startsWith('电话') && item2.startsWith('电话')){
                        item.disabled = true;
                    }
                    if(item.value.startsWith('账号') && item2.startsWith('账号')){
                        item.disabled = true;
                    }
                })
            });
        } else {
            this.searchValueOptions = [];
        }
        this.remoteSearchValueLoading = false;
    },

    checkAll(val, column){
        if(val){
            switch (column) {
                case 'invoiceType':
                    this.dict.type.invoice_type.map((dict, index) => {
                        this.form.invoiceTypeArr.push(dict.value)
                    });
                    break;
            }

        } else {
            switch (column) {
                case 'invoiceType':
                    this.form.invoiceTypeArr = []
                    break;
            }
        }
        switch (column) {
            case 'invoiceType':
                this.isInvoiceTypeIndeterminate = false;
                break;
        }

    },

    handleCheckedChange(value, column){
        let checkedCount = value.length;
        switch (column) {
            case 'invoiceType':
                this.checkAllInvoiceType = checkedCount === this.dict.type.invoice_type.length;
                this.isInvoiceTypeIndeterminate = checkedCount > 0 && checkedCount < this.dict.type.invoice_type.length;
                break;
        }

    }
  }
};
</script>
